<?php
// This controller handles the logic for the my products page

class MyProductsController extends Controller
{
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}
	
	public function actionSupplier()
	{
		if(Yii::app()->user->isGuest)
		{
			echo "Please Login first. We will redirect you to the login page in 3 secs";
			header("refresh:3;url=".Yii::app()->request->baseUrl);
		}
		else if(Yii::app()->user->userType=='b')
		{
			echo "you have no authority to view the supplier page";
		}
		else
		{
			$productTypes = ProductTypes::model()->with('products', 'products.orgProRelation')->findAll(
								'organization_ID='.Yii::app()->user->organizationID
							);
			$this->render('supplier', array('productTypes'=>$productTypes));
		}
	}
	
	public function actionDeleteProduct()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$productID=$_POST['product_ID'];
			$organizationID=Yii::app()->user->organizationID;
			$row=OrgProductRelation::model()->deleteByPk(array('product_ID'=>$productID, 'organization_ID'=>$organizationID));
			if($row==1)
				echo CJSON::encode('delete-product-success');
			else
				echo CJSON::encode('delete-product-fail');
		}
	}
	
	public function actionAddProduct()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$orgproductRelation=new OrgProductRelation;
			$orgproductRelation->product_ID=$_POST['product_ID'];
			$orgproductRelation->organization_ID=Yii::app()->user->organizationID;
			if($orgproductRelation->save())
			{
				$productTypes = ProductTypes::model()->with('products', 'products.orgProRelation')->findAll(
								'organization_ID='.Yii::app()->user->organizationID
							);
				echo $this->renderPartial('productlist', array('productTypes'=>$productTypes), true);
			}
			else
				echo 'add-product-fail';
		}
	}
	
	/*
	 * retrieve products by given a product category
	 */
	public function actionProducts()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$productTypeID=$_POST['product_category'];
			$res=ProductTypes::model()->getProductsByCategory($productTypeID);
			echo CJSON::encode($res);
		}
	}
}
?>
